"use client"

import { useState } from "react"
import { DataTable } from "@/components/common/data-table"
import { Button } from "@/components/ui/button"
import { Department } from "@/types/admin"
import { Plus } from "lucide-react"
import { columns } from "./columns"
import { DepartmentDialog } from "@/components/admin/department-dialog"
import { DeleteDialog } from "@/components/admin/delete-dialog"
import { useAdminStore } from "@/lib/store"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

export default function DepartmentsPage() {
  const { departments, deleteDepartment } = useAdminStore()
  
  const [openAddEditDialog, setOpenAddEditDialog] = useState(false)
  const [openDeleteDialog, setOpenDeleteDialog] = useState(false)
  const [selectedDepartment, setSelectedDepartment] = useState<Department | undefined>(undefined)

  const handleAddDepartment = () => {
    setSelectedDepartment(undefined)
    setOpenAddEditDialog(true)
  }

  const handleEditDepartment = (department: Department) => {
    setSelectedDepartment(department)
    setOpenAddEditDialog(true)
  }

  const handleDeleteClick = (department: Department) => {
    setSelectedDepartment(department)
    setOpenDeleteDialog(true)
  }

  const handleConfirmDelete = () => {
    if (selectedDepartment) {
      deleteDepartment(selectedDepartment.id)
      setOpenDeleteDialog(false)
    }
  }

  return (
    <div className="space-y-6">
      <Card className="card-shadow">
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-xl font-bold">部门管理</CardTitle>
          <Button 
            onClick={handleAddDepartment}
            className="rounded-lg bg-primary hover:bg-primary/90"
          >
            <Plus className="mr-2 h-4 w-4" /> 新增部门
          </Button>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground mb-4">管理组织内的所有部门。</p>
          <DataTable 
            columns={columns({ 
              onEdit: handleEditDepartment, 
              onDelete: handleDeleteClick 
            })} 
            data={departments}
            searchPlaceholder="搜索部门(支持部门名称、上级部门、部门主管等)"
          />
        </CardContent>
      </Card>

      <DepartmentDialog
        open={openAddEditDialog}
        onOpenChange={setOpenAddEditDialog}
        department={selectedDepartment}
        users={useAdminStore().users}
      />

      <DeleteDialog
        open={openDeleteDialog}
        onOpenChange={setOpenDeleteDialog}
        onConfirm={handleConfirmDelete}
        title="删除部门"
        description={`确定要删除部门 "${selectedDepartment?.name}" 吗？此操作不可撤销。`}
      />
    </div>
  )
} 